package com.jzo2o.foundations.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeSyncMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.domain.ServeSync;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author zhouge
 * @since 2025-05-18
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private ServeMapper serveMapper;

    @Resource
    private ServeItemMapper serveItemMapper;

    @Resource
    private RegionMapper regionMapper;

    @Resource
    private ServeSyncMapper serveSyncMapper;


    /**
     * 门户信息存入redis缓存
     * @param id
     * @return
     */
    @Cacheable(value = RedisConstants.CacheName.SERVE , key = "#id",
            cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Override
    public Serve QueryServeByIdCache(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO reqDTO) {

        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils.selectPage(reqDTO,
                () -> serveMapper.queryServeListByRegionId(reqDTO.getRegionId()));

        return serveResDTOPageResult;

    }

    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOS) {
        //遍历
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOS) {

            Long serveItemId = serveUpsertReqDTO.getServeItemId();
            //serve_item合法校验 如果未启用 则不能添加
            ServeItem serveItem = serveItemMapper.selectById(serveItemId);
            if(ObjectUtils.isNull(serveItem) || serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("服务项为空或服务项未启动不允许添加服务");
            }
            //同一个区域下不能添加相同的服务
            Integer count = lambdaQuery()
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .count();
            if(count > 0) {
                throw new ForbiddenOperationException(serveItem.getName()+"服务已存在");
            }

            //向serve表中插入数据

            Serve serve = BeanUtils.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            //插入数据
            baseMapper.insert(serve);
        }
    }

    @Override
    public Serve update(Long id, BigDecimal price) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!update){
            throw new CommonException("服务价格修改失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 区域服务上架 并将其放入缓存
     * @param id
     * @return
     */

    @Override
    @CachePut(value = RedisConstants.CacheName.SERVE,key="#id",
            cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Transactional
    public Serve onSale(Long id) {
        //根据id查询服务信息
        Serve serve = baseMapper.selectById(id);
        //区域服务存在且状态为0或1才能上架
        if(ObjectUtils.isNull(serve)) {
            throw new ForbiddenOperationException("服务信息不存在");
        }
        if(!(serve.getSaleStatus() == FoundationStatusEnum.INIT.getStatus()
                || serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) ) {
            throw new ForbiddenOperationException("区域服务状态是草稿或下架时才能上架");
        }
        //服务项没启用也不能上架
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("该服务的服务项启用才能上架");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("区域服务上架失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 服务下架 并删除缓存中的相关内容
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = RedisConstants.CacheName.SERVE,key = "#id")
    @Transactional
    public Serve offSale(Long id) {
        //根据id查询服务信息
        Serve serve = baseMapper.selectById(id);
        //区域服务存在且状态为2才能下架
        if(ObjectUtils.isNull(serve)) {
            throw new ForbiddenOperationException("服务信息不存在");
        }
        if(serve.getSaleStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("区域服务是上架状态才能下架");
        }
        //更新下架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("商品下架失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public void deleteById(Long id) {
        //查询服务信息
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtils.isNull(serve)) {
            throw new ForbiddenOperationException("服务信息不存在");
        }
        //服务状态为草稿时才能删除
        if(serve.getSaleStatus()!=FoundationStatusEnum.INIT.getStatus()){
            throw new ForbiddenOperationException("区域服务是草稿状态时才能删除");
        }
        //删除服务
        baseMapper.deleteById(id);
        //同步数据
        serveSyncMapper.deleteById(id);
    }

    @Override
    public void changeHotStatus(Long id, Integer flag) {

        //设置热门
        LambdaUpdateWrapper updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot,flag)
                .set(Serve::getHotTimeStamp,System.currentTimeMillis());
        super.update(updateWrapper);

        //同步数据
        ServeSync serveSync = new ServeSync();
        serveSync.setId(id);
        serveSync.setIsHot(flag);
        serveSync.setHotTimeStamp(System.currentTimeMillis());
        serveSyncMapper.updateById(serveSync);
    }
}
